package com.gaotu.demo.mybatis;

import com.gaotu.demo.User;
import com.gaotu.demo.UserDao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SqlSessionBasedUserDao implements UserDao {

    @Autowired
    private ResourceLoader resourceLoader;

    private SqlSessionFactory sqlSessionFactory;

    @PostConstruct
    public void init() throws Exception{
        Resource resource = resourceLoader.getResource("classpath:/mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(resource.getInputStream());
        this.sqlSessionFactory  = sqlSessionFactory;
    }
    @Override
    public void insert(User user) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)){
            sqlSession
                    .insert("com.gaotu.demo.mybatis.mapper.UserMapper.insert", user);
        }
    }
    @Override
    public User getById(Long id) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)){
            List<User> users =  sqlSession
                    .selectList("com.gaotu.demo.mybatis.mapper.UserMapper.selectByPrimaryKey", id);
            return users.isEmpty() ? null : users.get(0);
        }
    }

    @Override
    public void update(User user) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)){
            sqlSession.update("com.gaotu.demo.mybatis.mapper.UserMapper.updateByPrimaryKey", user);
        }
    }

    @Override
    public void deleteById(Long id) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)){
            sqlSession.delete("com.gaotu.demo.mybatis.mapper.UserMapper.deleteByPrimaryKey", id);
        }
    }


    @Override
    public User getByName(String name) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)){
            List<User> users =  sqlSession.selectList("com.gaotu.demo.mybatis.mapper.UserMapper.selectByName", name);
            return users.isEmpty() ? null : users.get(0);
        }
    }
}
